'''
kNN: k Nearest Neighbors

Input:      inX: vector to compare to existing dataset (1xN)
            dataSet: size m data set of known vectors (NxM)
            labels: data set labels (1xM vector)
            k: number of neighbors to use for comparison (should be an odd number)

Output:     the most popular class label

'''
from numpy import *
import numpy as np
import operator
import matplotlib.pyplot as plt
from os import listdir


def classify0(inX, dataSet, labels, k):
    '''
    :param inX: 用于分类的输入向量
    :param dataSet: 输入的训练样本集
    :param labels: 标签向量
    :param k: 用于选择最近邻居的数目
    :return:
    '''
    dataSetSize = dataSet.shape[0]
    diffMat = tile(inX, (dataSetSize,1)) - dataSet
    sqDiffMat = diffMat**2
    sqDistances = sqDiffMat.sum(axis=1)
    distances = sqDistances**0.5
    # argsort()函数： 对数组中的元素进行从小到大排序，并返回相应序列元素的数组下标。
    sortedDistIndicies = distances.argsort()
    classCount={}

    # 确定前k个距离最小元素所在的分类
    for i in range(k):
        voteIlabel = labels[sortedDistIndicies[i]]
        classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1

    # 得出classCount = {'B':2,'A':1}
    '''
    sorted(iterable, cmp=None, key=None, reverse=False)
    参数说明：
    iterable -- 可迭代对象。
    cmp -- 比较的函数，这个具有两个参数，参数的值都是从可迭代对象中取出，此函数必须遵守的规则为，大于则返回1，小于则返回-1，等于则返回0。
    key -- 主要是用来进行比较的元素，只有一个参数，具体的函数的参数就是取自于可迭代对象中，指定可迭代对象中的一个元素来进行排序。
    reverse -- 排序规则，reverse = True 降序 ， reverse = False 升序（默认）。
    '''

    # classCount对象分解为元组列表
    # operator.itemgetter(1)得到字典中的value值，并按照这个排序
    sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]

def createDataSet():
    group = array([[1.0,1.1], [1.0,1.0], [0,0], [0,0.1]])
    labels = ['A', 'A', 'B', 'B']
    return group, labels


def file2matrix(filename):
    '''
    将文本记录转换为Numpy的解析程序
    :param filename: 输入的文件
    :return:
    '''
    fr = open(filename)
    # 得到文件的行数
    numberOfLines = len(fr.readlines())

    # 得到一个numberOfLines行，3列的numpy矩阵，填充值为0
    returnMat = zeros((numberOfLines, 3))
    classLabelVectory = []
    fr = open(filename)
    index = 0

    # 循环处理每行字符
    for line in fr.readlines():
        # line.strip()截取掉所有的回车字符，（包括'\n', '\r', '\t', ' ')
        line = line.strip()
        # 将line中整行的数据，根据tab字符\t，分割成一个元素列表
        listFormLine = line.split('\t')
        # 将每行的前三个元素存储到特征矩阵returnMat中
        returnMat[index,:] = listFormLine[0:3]
        # 将每行的最后一个元素存储到classLabelVectory中
        classLabelVectory.append(int(listFormLine[-1]))
        index += 1
    return returnMat, classLabelVectory


def autoNorm(dataSet):
    '''
    归一化数值：将数字特征值转化为0到1的区间
    :param dataSet: 输入的数据
    :return:
    '''
    # 将每列中的最小值变量放在minVals中，最大值变量放在maxVals中，得到的是1*3类型的数据
    minVals = dataSet.min(0)
    # min(0),max(0)中的参数0使得函数可以在列中选择最小值和最大值
    maxVals = dataSet.max(0)
    ranges = maxVals-minVals
    normDataSet = zeros(shape(dataSet))
    m = dataSet.shape[0]
    # tile()函数将minVals中的内容复制转换成和dataSet一样的矩阵类型
    vals = tile(minVals, (m,1))
    normDataSet = dataSet - tile(minVals, (m,1))
    normDataSet = normDataSet/tile(ranges, (m,1))
    return normDataSet, ranges, minVals


def datingClassTest():
    '''
    分类器对于约会网站的测试代码
    :return:
    '''
    hoRatio = 0.05
    datingDataMat, datingLabels = file2matrix('ch02/datingTestSet2.txt')
    normMat, ranges, minVals = autoNorm(datingDataMat)
    m = normMat.shape[0]
    numTestVecs = int(m*hoRatio)
    errorCount = 0.0
    # normMat中前numTestVecs行数据用于测试，numTestVecs~m行数据用于训练
    for i in range(numTestVecs):
        classifierResult = classify0(normMat[i,:], normMat[numTestVecs:m,:], datingLabels[numTestVecs:m], 4)
        print("classifierResult: %d, datingLabels: %d" %( classifierResult, datingLabels[i]))
        if(classifierResult != datingLabels[i]): errorCount += 1.0
    print("the total error rate is: %f" % (errorCount/float(numTestVecs)))
    print(errorCount)


def classifyPerson():
    '''
    约会网站预测函数
    :return:
    '''
    resultList = ['not at all', 'in small doses', 'in large doses']
    percentTats = float(input("percentage of time spent playing video games? "))
    ffMiles = float(input("frequent filer miles earned per year? "))
    iceCream = float(input("Liters of ice cream consumed per year? "))
    datingDataMat, datingLabels = file2matrix('ch02/datingTestSet2.txt')
    normMat, ranges, minVals = autoNorm(datingDataMat)
    inArr = array([ffMiles, percentTats, iceCream])
    classiferResult = classify0((inArr-minVals)/ranges, normMat, datingLabels, 3)
    print("You will probably like this person: ", resultList[classiferResult-1])


def img2vector(filename):
    returnVect = zeros((1,1024))
    fr = open(filename)
    # 循环读出文件中前32行，并将每行头32个字符存储在returnVect数组中
    for i in range(32):
        # 读取文件中第i行的数据
        lineStr = fr.readline()
        for j in range(32):
            returnVect[0,32*i+j] = int(lineStr[j])
    return returnVect


def handwritingClassTest():
    hwLabels = []
    # 将trainingDigits目录中的文件内容存储在列表中
    trainingFileList = listdir('trainingDigits')
    # m是trainingDigits中文件的个数
    m = len(trainingFileList)
    # 创建一个m行1024列的训练矩阵
    trainingMat = zeros((m,1024))
    for i in range(m):
        # 从文件名中解析出分类数字
        fileNameStr = trainingFileList[i]
        fileStr = fileNameStr.split('.')[0]
        classNumStr = int(fileStr.split('_')[0])
        hwLabels.append(classNumStr)
        trainingMat[i,:] = img2vector('trainingDigits/%s' % fileNameStr)
    testFileList = listdir('testDigits')
    errorCount = 0.0
    mTest = len(testFileList)
    for i in range(mTest):
        fileNameStr = testFileList[i]
        fileStr = fileNameStr.split('.')[0]
        classNumStr = int(fileStr.split('_')[0])
        vectorUnderTest = img2vector('testDigits/%s' % fileNameStr)
        classifierResult = classify0(vectorUnderTest, trainingMat, hwLabels, 3)
        print("the classifier came back with: %d, the real answer is: %d" % (classifierResult, classNumStr))
        if(classifierResult != classNumStr): errorCount += 1.0
    print("\nthe total number of errors is: %d" % errorCount)
    print("\nthe total error rate is: %f" % (errorCount / float(mTest)))



if __name__ == '__main__':
    group, labels = createDataSet()
    classify0([0,0], group, labels, 3)

    datingDataMat, datingLabels = file2matrix('ch02/datingTestSet2.txt')
    datingDataMat = np.array(datingDataMat)
    datingLabels = np.array(datingLabels)
    # print(datingDataMat)
    # print()
    # print(datingLabels[:20])

    fig = plt.figure()
    '''    
    plt.subplot(nrows, ncols, index)
    nrows 与 ncols 表示要划分几行几列的子区域（nrows*nclos表示子图数量），
    index 的初始值为1，用来选定具体的某个子区域。
    '''
    ax = fig.add_subplot(111)
    # ax.scatter(datingDataMat[:,1], datingDataMat[:,2], 15.0*array(datingLabels), 15.0*array(datingLabels))
    # 使用datingDataMat矩阵第二列和第三列展示数据，
    # 然后用变量datingLabels存储的类标签属性，在散点图中绘制色彩、尺寸不同的点
    ax.scatter(datingDataMat[:, 0], datingDataMat[:, 1], 15.0 * array(datingLabels), 15.0 * array(datingLabels))
    plt.show()

    normMat, ranges, minVals = autoNorm(datingDataMat)
    # print(normMat)
    # print(ranges)
    # print(minVals)

    # 测试约会网站的效率
    # datingClassTest()

    # classifyPerson()

    # handwritingClassTest()


